from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from .models import Repository, History
from .serializers import RepoSerializer, HistorySerializer, HistoryDetailSerializer
from datetime import datetime
from rest_framework.decorators import action
from rest_framework.response import Response
from .tasks import run_playbook


class RepoViewSet(ModelViewSet):
    queryset = Repository.objects.all()
    serializer_class = RepoSerializer

    @action(detail=True, url_path='exec', methods=["POST"])
    def execute(self, request, pk=None):
        instance: Repository = self.get_object()
        print(instance.pk, instance.project_name, instance.repo_url)
        # 异步提交任务
        task = run_playbook.apply_async((pk, instance.repo_url, request.user.id))
        print(f"{type(task)}: {task}. {datetime.now()}")
        return Response({"task_id": task.task_id})


class HistoryViewSet(ReadOnlyModelViewSet):
    queryset = History.objects.all()
    serializer_class = HistorySerializer

    def get_serializer_class(self):
        return HistoryDetailSerializer if "pk" in self.kwargs else HistorySerializer
